package com.pic.mgt.monitor.parser.syushin;

import org.apache.commons.lang.StringUtils;

import com.pic.mgt.monitor.WrongUnitFormatException;
import com.pic.mgt.monitor.parser.FormatParser;

public final class SyushinMessageBusinessTypeParser extends FormatParser {
	private int realMessageFilenameLen;
	private int bucketMessageFilenameLen;
	private String messageTransOkConfirmationFilenameSuffix;
	private int realMessageBusinessTypeAtChar;
	private int bucketMessageBusinessTypeAtChar;
	
	@Override
	public Object parse(Object _messageConfirmationFilename) throws WrongUnitFormatException {
		// 確認是否為 String 型態
		// throws WrongUnitFormatException
		super.checkObjectType(_messageConfirmationFilename, String.class);
		
		String messageConfirmationFilename = (String)_messageConfirmationFilename;
		
		// 取得交易檔檔名
		String transactionFilename = StringUtils.removeEnd(messageConfirmationFilename,
														   this.messageTransOkConfirmationFilenameSuffix);
		
		// 取得業務型態字元
		String businessTypeChar = null;
		
		// 假設是 real 的 message
		try {
			if (transactionFilename.length() == this.realMessageFilenameLen ) {
				businessTypeChar = String.valueOf(
									transactionFilename.charAt(this.realMessageBusinessTypeAtChar - 1));
			}
		} catch (IndexOutOfBoundsException e1) {
			// 代表不是 real 的 Message
		}
		
		// 假設是 bucket 的 message
		try {
			if (transactionFilename.length() == this.bucketMessageFilenameLen ) {
				businessTypeChar = String.valueOf(
									transactionFilename.charAt(this.bucketMessageBusinessTypeAtChar - 1));
			}
		} catch (IndexOutOfBoundsException e1) {
			// 代表不是 bucket 的 Message
		}
		
		if (businessTypeChar != null) {
			return businessTypeChar;
		}
		else {
			throw new WrongUnitFormatException(
					"The confirmation filename '" + messageConfirmationFilename +
					"' of message is not correct!");
		}
	}
	
	// --- getter and setter ---

	public void setRealMessageFilenameLen(int realMessageFilenameLen) {
		this.realMessageFilenameLen = realMessageFilenameLen;
	}

	public void setBucketMessageFilenameLen(int bucketMessageFilenameLen) {
		this.bucketMessageFilenameLen = bucketMessageFilenameLen;
	}

	public void setMessageTransOkConfirmationFilenameSuffix(
			String messageTransOkConfirmationFilenameSuffix) {
		this.messageTransOkConfirmationFilenameSuffix = messageTransOkConfirmationFilenameSuffix;
	}

	public void setRealMessageBusinessTypeAtChar(int realMessageBusinessTypeAtChar) {
		this.realMessageBusinessTypeAtChar = realMessageBusinessTypeAtChar;
	}

	public void setBucketMessageBusinessTypeAtChar(
			int bucketMessageBusinessTypeAtChar) {
		this.bucketMessageBusinessTypeAtChar = bucketMessageBusinessTypeAtChar;
	}

}
